import { _decorator, Component, Node, director, find } from 'cc';
import { BattleScene } from './BattleScene';
import { LOG } from '../../ConsoleLogCtrl';

const { ccclass, property } = _decorator;

/**
 * 战斗场景管理器
 * 提供获取战斗场景实例的方法
 */
@ccclass('BattleSceneManager')
class BattleSceneManager {
    private static _instance: BattleSceneManager = null;
    private _battleScene: BattleScene = null;
    
    /**
     * 获取战斗场景管理器实例
     */
    public static getInstance(): BattleSceneManager {
        if (!this._instance) {
            this._instance = new BattleSceneManager();
        }
        return this._instance;
    }
    
    /**
     * 初始化战斗场景
     * @param battleSceneNode 战斗场景节点
     */
    public init(battleSceneNode: Node): void {
        if (!battleSceneNode) {
            LOG.error('战斗场景节点不存在');
            return;
        }
        
        this._battleScene = battleSceneNode.getComponent(BattleScene);
        if (!this._battleScene) {
            LOG.error('战斗场景组件不存在');
            return;
        }
        
        LOG.log('战斗场景初始化成功');
    }
    
    /**
     * 获取战斗场景实例
     */
    public getBattleScene(): BattleScene {
        if (!this._battleScene) {
            // 尝试从场景中查找战斗场景节点
            // 首先尝试查找Canvas节点，因为BattleScene组件可能直接挂在Canvas上
            const canvasNode = find('Canvas');
            if (canvasNode) {
                const battleSceneComponent = canvasNode.getComponent(BattleScene);
                if (battleSceneComponent) {
                    this._battleScene = battleSceneComponent;
                    LOG.log('在Canvas节点上找到BattleScene组件');
                } else {
                    // 尝试在Canvas的子节点中查找
                    const battleSceneNode = find('Canvas/BattleScene');
                    if (battleSceneNode) {
                        this.init(battleSceneNode);
                    } else {
                        LOG.error('未找到战斗场景节点，请确保已加载战斗场景并且Canvas节点上挂载了BattleScene组件');
                    }
                }
            } else {
                LOG.error('未找到Canvas节点，请确保已加载战斗场景');
            }
        }
        return this._battleScene;
    }
    
    /**
     * 清理战斗场景
     */
    public clear(): void {
        this._battleScene = null;
    }
}

// 导出单例实例
export const battleScene = BattleSceneManager.getInstance();